package cn.schoolwow.quickdao.module.database.ddl.common.flow;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.module.database.ddl.query.service.entity.GetTableNameListFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.ArrayList;
import java.util.List;

public class GetDatabaseEntityFromCacheFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        getSpecificTableFromCache(flowContext);
        getAllTableFromCache(flowContext);
    }

    @Override
    public String name() {
        return "从缓存中获取数据库表信息";
    }

    private void getSpecificTableFromCache(FlowContext flowContext){
        String tableName = (String) flowContext.getData("tableName");
        if(null==tableName){
            return;
        }
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        String columnName = (String) flowContext.getData("columnName");

        if(quickDAOConfig.databaseContext.databaseTableCache.containsKey(tableName)){
            Entity entity = quickDAOConfig.databaseContext.databaseTableCache.get(tableName);
            if(null==columnName){
                flowContext.putData("entity", entity);
                flowContext.broken("从缓存中获取指定表信息");
            }else{
                Property property = entity.getPropertyByFieldNameOrColumnName(columnName);
                if(null!=property){
                    flowContext.putData("property", property);
                    flowContext.broken("从缓存中获取指定表的指定字段信息");
                }
                flowContext.brokenCurrentFlow("缓存中不存在指定表的指定字段信息");
            }
        }
    }

    private void getAllTableFromCache(FlowContext flowContext){
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);

        List<String> tableNameList = (List<String>) flowContext.executeFlowList(new GetTableNameListFlow()).getData("tableNameList");
        if(!tableNameList.isEmpty()&&tableNameList.size()==quickDAOConfig.databaseContext.databaseTableCache.size()){
            List<Entity> entityList = new ArrayList<>();
            entityList.addAll(quickDAOConfig.databaseContext.databaseTableCache.values());
            flowContext.putData("entityList", entityList);
            flowContext.broken("从缓存中获取所有表信息");
        }
    }
}
